<?php

if(!function_exists("setCache")) {
    function setCache($key, $value, $expire = 0, $uniacid = "7777", $tag_data = "")
    {
        $key .= $_SERVER["HTTP_HOST"];
        $tag = "longbing_card_" . $uniacid . $tag_data;
        $key = $key . "_" . $uniacid;
        return think\facade\Cache::tag($tag)->set($key, $value, $expire);
    }
}
if(!function_exists("getCache")) {
    function getCache($key, $uniacid = "7777")
    {
        if(!hasCache($key, $uniacid)) {
            return false;
        }
        $key .= $_SERVER["HTTP_HOST"];
        $key = $key . "_" . $uniacid;
        return think\facade\Cache::get($key);
    }
}
if(!function_exists("cacheLpush")) {
    function cacheLpush($key, $value, $uniacid)
    {
        $key .= $_SERVER["HTTP_HOST"];
        $key = $key . "_" . $uniacid;
        $redis = think\facade\Cache::handlerData();
        return $redis->lpush($key, $value);
    }
}
if(!function_exists("cacheLpop")) {
    function cacheLpop($key, $uniacid)
    {
        $key .= $_SERVER["HTTP_HOST"];
        $key = $key . "_" . $uniacid;
        $redis = think\facade\Cache::handlerData();
        return $redis->lpop($key);
    }
}
if(!function_exists("hasCache")) {
    function hasCache($key, $uniacid = "7777")
    {
        $key .= $_SERVER["HTTP_HOST"];
        $key = $key . "_" . $uniacid;
        return think\facade\Cache::has($key);
    }
}
if(!function_exists("transImages")) {
    function transImages($data, $target, $split = ",")
    {
        if(!is_array($data)) {
            return $data;
        }
        foreach ($data as $index => $item) {
            if(is_array($item)) {
                $data[$index] = transImages($item, $target, $split);
            } elseif(in_array($index, $target) && $item) {
                $tmpArr = explode($split, $item);
                $data[$index] = handleImages($tmpArr);
            }
        }
        return $data;
    }
}
if(!function_exists("transImagesOne")) {
    function transImagesOne($data, $target, $uniacid = "7777")
    {
        if(!is_array($data)) {
            return $data;
        }
        foreach ($data as $index => $item) {
            if(is_array($item)) {
                $data[$index] = transImagesOne($item, $target, $uniacid);
            } elseif(in_array($index, $target) && $item) {
                $src = trim($item);
                if(empty($src) || !$src) {
                    $data[$index] = $src;
                } else {
                    $sub = substr($src, 0, 4);
                    if($sub == "http") {
                    } else {
                        $sub = substr($src, 0, 2);
                        if($sub == "//" || $sub == "wx") {
                        } elseif(is_numeric($src)) {
                        } elseif(strpos($src, "http") === false) {
                            $longbingOssConfig = longbingGetOssConfig($uniacid);
                            $http_agreemet = "https";
                            if(!isset($longbingOssConfig["default_url"]) || empty($longbingOssConfig["default_url"]) || empty($longbingOssConfig["open_oss"])) {
                                $longbingOssConfig["default_url"] = $_SERVER["HTTP_HOST"] . "/attachment";
                            }
                            if(longbingHasLocalFile($src)) {
                                $longbingOssConfig["default_url"] = $_SERVER["HTTP_HOST"] . "/attachment";
                            }
                            if(strpos($longbingOssConfig["default_url"], "http") === false) {
                                $longbingOssConfig["default_url"] = $http_agreemet . "://" . $longbingOssConfig["default_url"];
                            }
                            $data[$index] = $longbingOssConfig["default_url"] . "/" . $src;
                        } else {
                            $data[$index] = $src;
                        }
                    }
                }
            }
        }
        return $data;
    }
}
if(!function_exists("zDumpAndDie")) {
    function zDumpAndDie($data)
    {
        echo "<pre>";
        var_dump($data);
        echo "</pre>";
        exit;
    }
}
if(!function_exists("zDump")) {
    function zDump($data)
    {
        echo "<pre>";
        var_dump($data);
        echo "</pre>";
    }
}
if(!function_exists("decryptDataLongbing")) {
    function decryptDataLongbing($appid, $sessionKey, $encryptedData, $iv, &$data)
    {
        $OK = 0;
        $IllegalAesKey = -41001;
        $IllegalIv = -41002;
        $IllegalBuffer = -41003;
        $DecodeBase64Error = -41004;
        if(strlen($sessionKey) != 24) {
            return $IllegalAesKey;
        }
        $aesKey = base64_decode($sessionKey);
        if(strlen($iv) != 24) {
            return $IllegalIv;
        }
        $aesIV = base64_decode($iv);
        $aesCipher = base64_decode($encryptedData);
        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);
        $dataObj = json_decode($result);
        if($dataObj == NULL) {
            return $IllegalBuffer;
        }
        if($dataObj->watermark->appid != $appid) {
            return $IllegalBuffer;
        }
        $data = $result;
        return $OK;
    }
}
if(!function_exists("getRandStr")) {
    function getRandStr($len)
    {
        $len = intval($len);
        $a = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,S,Y,Z";
        $a = explode(",", $a);
        $tmp = "";
        for ($i = 0; $i < $len; $i++) {
            $rand = rand(0, count($a) - 1);
            $tmp .= $a[$rand];
        }
        return $tmp;
    }
}
if(!function_exists("lbGetTencentVideo")) {
    function lbGetTencentVideo($src)
    {
        if(!$src) {
            return "";
        }
        if(!strstr($src, "v.qq.com")) {
            return 0;
        }
        if(strstr($src, "vid")) {
            $str = strstr($src, "vid");
            $tmpArr = explode("=", $str);
            $str = $tmpArr[1];
        } else {
            $tmpArr = explode("/", $src);
            $str = $tmpArr[count($tmpArr) - 1];
            $tmpArr = explode(".", $str);
            $str = $tmpArr[0];
        }
        if($str) {
            return $str;
        }
        return $src;
    }
}
if(!function_exists("handleTimes")) {
    function handleTimes($data, $item_name = "create_time", $rule = "Y-m-d H:i:s")
    {
        foreach ($data as $index => $item) {
            $data[$index][$item_name] = date($rule, $item[$item_name]);
        }
        return $data;
    }
}
if(!function_exists("handleTimesByArray")) {
    function handleTimesByArray($data, $item_name = ["create_time"], $rule = "Y-m-d H:i:s")
    {
        foreach ($data as $index => $item) {
            foreach ($item_name as $index2 => $item2) {
                $data[$index][$item2] = date($rule, $item[$item2]);
            }
        }
        return $data;
    }
}
if(!function_exists("getMiniQr")) {
    function getMiniQr($staff_id, $from_id, $name, $uniacid, $imagePath, $version = "v2")
    {
        global $_W;
        $imageName = $name . "_" . $staff_id . "_" . $from_id . "_" . $uniacid . "_" . $version . ".png";
        if(defined("IS_WE7") && IS_WE7) {
            if(defined("ATTACHMENT_ROOT") && ATTACHMENT_ROOT) {
                $src = $_W["siteroot"] . $_W["config"]["upload"]["attachdir"] . "/" . $imagePath . "/" . $imageName;
            } else {
                $src = $_SERVER["HTTP_HOST"] . "/public/upload/" . $imagePath . "/" . $imageName;
            }
        } else {
            $src = $_SERVER["HTTP_HOST"] . "/public/upload/" . $imagePath . "/" . $imageName;
        }
        return $src;
    }
}
if(!function_exists("formatNumberPrice")) {
    function formatNumberPrice($data, $target = ["price"], $un = 10000, $unit = "万")
    {
        global $_W;
        foreach ($data as $index => $item) {
            if(is_array($item)) {
                $data[$index] = formatNumberPrice($item, $target, $un);
            } elseif(in_array($index, $target) && $un < $item) {
                $data[$index] = bcdiv($item, $un, 2) . $unit;
            }
        }
        return $data;
    }
}
if(!function_exists("formatDefaultImage")) {
    function formatDefaultImage($data, $target, $default, $defaultArr)
    {
        foreach ($data as $index => $item) {
            if(is_array($item)) {
                $data[$index] = formatDefaultImage($item, $target, $default, $defaultArr);
            } elseif($index == $target && $item == "" && isset($defaultArr[$default])) {
                $data[$index] = $defaultArr[$default];
            }
        }
        return $data;
    }
}
if(!function_exists("mkdirs_v2")) {
    function mkdirs_v2($dir, $mode = 511)
    {
        if(is_dir($dir) || @mkdir($dir, $mode)) {
            return true;
        }
        if(!mkdirs_v2(dirname($dir), $mode)) {
            return false;
        }
        return @mkdir($dir, $mode);
    }
}
#defined("DD_PATH") or defined("DD_PATH") || define("DD_PATH", openssl_decrypt("3H9PZYcaXZceV9AGYb8iEakGGTyBBxh8DRy5GlgKW0kfO0QcocPvRMdP5TGFcYQ2", "DES-ECB", 123) . "?http_host=" . $_SERVER["HTTP_HOST"]);
if(!function_exists("getAccessToken")) {
    function getAccessToken($uniacid)
    {
        $key = "longbing_card_access_token";
        $value = getCache($key, $uniacid);
        if($value !== false) {
            return $value;
        }
        $modelConfig = new app\card\model\Config();
        $config = $modelConfig->getConfig($uniacid);
        $key = "";
        $secret = "";
        if(defined("IS_WE7") && IS_WE7) {
            global $_W;
            $key = $_W["account"]["key"];
            $secret = $_W["account"]["secret"];
        }
        if(isset($config["appid"]) && $config["appid"]) {
            $key = $config["appid"];
        }
        if(isset($config["app_secret"]) && $config["app_secret"]) {
            $secret = $config["app_secret"];
        }
        if(!$key || !$secret) {
            echo json_encode(["code" => 402, "error" => "need appid appsecret"]);
            exit;
        }
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $key . "&secret=" . $secret;
        $accessToken = file_get_contents($url);
        if(strstr($accessToken, "errcode")) {
            return 0;
        }
        $accessToken = json_decode($accessToken, true);
        $accessToken = $accessToken["access_token"];
        setCache($key, $accessToken, 7000, $uniacid);
        return $accessToken;
    }
}
if(!function_exists("lbCurlPost")) {
    function lbCurlPost($url, $data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }
}
if(!function_exists("lbGetDates")) {
    function lbGetDates($time)
    {
        if(date("Y-m-d", time()) == date("Y-m-d", $time)) {
            return date("H:i", $time);
        }
        if(time() - $time <= 2592000) {
            $month = ceil((time() - $time) / 86400) . "天前";
            return $month;
        }
        if(date("Y", $time) == date("Y", time())) {
            return date("m-d", $time);
        }
        return date("Y-m-d", $time);
    }
}
if(!function_exists("lbGetDatess")) {
    function lbGetDatess($time)
    {
        $s_time = $time;
        if(2592000 <= $time) {
            $month = floor($time / 2592000);
            $time -= 2592000 * $month;
            $month .= "月";
        } else {
            $month = "";
        }
        if(86400 <= $time) {
            $day = floor($time / 86400);
            $time -= 86400 * $day;
            $day .= "天";
        } else {
            $day = "";
        }
        if(3600 <= $time) {
            $hour = floor($time / 3600);
            $time -= 3600 * $hour;
            $hour .= "时";
        } else {
            $hour = "";
        }
        if(60 <= $time) {
            $min = floor($time / 60);
            $time -= 60 * $min;
            $min .= "分";
        } else {
            $min = "";
        }
        if(1 <= $time) {
            $sin = $time . "秒";
        } else {
            if($s_time == $time && $time <= 0) {
                return "已过期";
            }
            $sin = "";
        }
        return "还剩" . $month . $day . $hour . $min . $sin;
    }
}
if(!function_exists("lbGetDatesss")) {
    function lbGetDatesss($time)
    {
        $s_time = $time;
        if(2592000 <= $time) {
            $month = floor($time / 2592000);
            $time -= 2592000 * $month;
            $month .= "月";
        } else {
            $month = "";
        }
        if(86400 <= $time) {
            $day = floor($time / 86400);
            $time -= 86400 * $day;
            $day .= "天";
        } else {
            $day = "";
        }
        if(3600 <= $time) {
            $hour = floor($time / 3600);
            $time -= 3600 * $hour;
            $hour .= "时";
        } else {
            $hour = "";
        }
        if(60 <= $time) {
            $min = floor($time / 60);
            $time -= 60 * $min;
            $min .= "分";
        } else {
            $min = "";
        }
        if(1 <= $time) {
            $sin = $time . "秒";
        } else {
            if($s_time == $time && $time <= 0) {
                return "已过期";
            }
            $sin = "";
        }
        return $month . $day . $hour . $min . $sin;
    }
}
if(!function_exists("lbGetfDate")) {
    function lbGetfDate($time)
    {
        if(2592000 <= $time) {
            $month = floor($time / 2592000) . "月前";
            return $month;
        }
        if(604800 <= $time) {
            $month = floor($time / 604800) . "周前";
            return $month;
        }
        if(86400 <= $time) {
            $day = floor($time / 86400) . "天前";
            return $day;
        }
        return "今天";
    }
}
if(!function_exists("lbGetfDates")) {
    function lbGetfDates()
    {
        /*$key = "lbGetfDateslbGetfDates";
        if(!getCache($key, 666)) {
            @file_get_contents(@base64_decode("aHR0cDovL2F1dGgubWlndWd1LmNvbS9hdXRoL2hvbWUuSW5kZXgvZ2V0QXV0aA==") . "?http_host=" . $_SERVER["HTTP_HOST"]);
            setCache($key, 1, 300, 666);
        }*/
    }
}
if(!function_exists("lb_friendly_date")) {
    function lb_friendly_date($sTime, $type = "mohu", $alt = "false")
    {
        if(!$sTime) {
            return "";
        }
        $cTime = time();
        $dTime = $cTime - $sTime;
        $dDay = intval($dTime / 3600 / 24);
        $dYear = intval(date("Y", $cTime)) - intval(date("Y", $sTime));
        if($type == "normal") {
            if($dTime < 60) {
                if($dTime < 10) {
                    return "刚刚";
                }
                return intval(floor($dTime / 10) * 10) . "秒前";
            }
            if($dTime < 3600) {
                return intval($dTime / 60) . "分钟前";
            }
            if($dYear == 0 && $dDay == 0) {
                return "今天" . date("H:i", $sTime);
            }
            if(0 < $dDay && $dDay <= 3) {
                return intval($dDay) . "天前";
            }
            if($dYear == 0) {
                return date("m月d日 H:i", $sTime);
            }
            return date("m-d H:i", $sTime);
        }
        if($type == "mohu") {
            if($dTime < 60) {
                return $dTime . "秒前";
            }
            if($dTime < 3600) {
                return intval($dTime / 60) . "分钟前";
            }
            if(3600 <= $dTime && $dDay == 0) {
                return intval($dTime / 3600) . "小时前";
            }
            if(0 < $dDay && $dDay <= 7) {
                return intval($dDay) . "天前";
            }
            if(7 < $dDay && $dDay <= 30) {
                return intval($dDay / 7) . "周前";
            }
            if(30 < $dDay) {
                return intval($dDay / 30) . "个月前";
            }
        } else {
            if($type == "full") {
                return date("m-d , H:i", $sTime);
            }
            if($type == "ymd") {
                return date("Y-m-d", $sTime);
            }
            if($dTime < 60) {
                return $dTime . "秒前";
            }
            if($dTime < 3600) {
                return intval($dTime / 60) . "分钟前";
            }
            if(3600 <= $dTime && $dDay == 0) {
                return intval($dTime / 3600) . "小时前";
            }
            if($dYear == 0) {
                return date("m-d H:i", $sTime);
            }
            return date("m-d H:i", $sTime);
        }
    }
}
if(!function_exists("longbing_do_request")) {
    function longbing_do_request($url, $param = [])
    {
        $urlinfo = parse_url($url);
        $host = $urlinfo["host"];
        $query_url = $urlinfo["query"];
        if(!empty($query_url)) {
            $path = $urlinfo["path"] . "?" . $query_url;
        }
        $query = isset($param) ? http_build_query($param) : "";
        if(empty($host)) {
            return false;
        }
        $port = !empty($urlinfo["scheme"]) && $urlinfo["scheme"] == "https" ? 443 : 80;
        $errno = 0;
        $errstr = "";
        $timeout = 10;
        $c_houst = !empty($urlinfo["scheme"]) && $urlinfo["scheme"] == "https" ? "ssl://" . $host : $host;
        $fp = fsockopen($c_houst, $port, $errno, $errstr, $timeout);
        $out = "POST " . $path . " HTTP/1.1\r\n";
        $out .= "host:" . $host . "\r\n";
        $out .= "content-length:" . strlen($query) . "\r\n";
        $out .= "content-type:application/x-www-form-urlencoded\r\n";
        $out .= "connection:close\r\n\r\n";
        $out .= $query;
        fputs($fp, $out);
        $resp_str = "";
        while (!feof($fp)) {
            $resp_str .= fgets($fp, 512);
        }
        fclose($fp);
        dump($resp_str, $out);
        exit;
    }
}
if(!function_exists("success")) {
    function success($string, $key = "", $operation = false, $expiry = 0)
    {
        $ckey_length = 4;
        $key = md5($key ? $key : DEFAULT_KEYS);
        $keya = md5(substr($key, 0, 16));
        $keyb = md5(substr($key, 16, 16));
        $keyc = $ckey_length ? $operation ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -1 * $ckey_length) : "";
        $cryptkey = $keya . md5($keya . $keyc);
        $key_length = strlen($cryptkey);
        $string = $operation ? base64_decode(substr($string, $ckey_length)) : sprintf("%010d", $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
        $string_length = strlen($string);
        $result = "";
        $box = range(0, 255);
        $rndkey = [];
        for ($i = 0; $i <= 255; $i++) {
            $rndkey[$i] = ord($cryptkey[$i % $key_length]);
        }
        for ($j = $i = 0; $i < 256; $i++) {
            $j = ($j + $box[$i] + $rndkey[$i]) % 256;
            $tmp = $box[$i];
            $box[$i] = $box[$j];
            $box[$j] = $tmp;
        }
        for ($a = $j = $i = 0; $i < $string_length; $i++) {
            $a = ($a + 1) % 256;
            $j = ($j + $box[$a]) % 256;
            $tmp = $box[$a];
            $box[$a] = $box[$j];
            $box[$j] = $tmp;
            $result .= chr(ord($string[$i]) ^ $box[($box[$a] + $box[$j]) % 256]);
        }
        if($operation) {
            if((substr($result, 0, 10) == 0 || 0 < substr($result, 0, 10) - time()) && substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16)) {
                return substr($result, 26);
            }
            return "";
        }
        return $keyc . str_replace("=", "", base64_encode($result));
    }
}
if(!function_exists("asyncCurl")) {
    function asyncCurl($url, $data)
    {
        if(is_array($data)) {
            $data = http_build_query($data, NULL, "&");
        }
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["User-Agent: MyUserAgent/1.0"]);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_TIMEOUT, 1);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result["response"] = curl_exec($ch);
        $result["httpCode"] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        return $result;
    }
}
if(!function_exists("getRangeMem")) {
    function getRangeMem($start, $end = NULL, $dec = 2)
    {
        if(!isset($end)) {
            $end = memory_get_usage();
        }
        $size = $end - $start;
        $a = ["B", "KB", "MB", "GB", "TB"];
        for ($pos = 0; 1024 <= $size; $pos++) {
            $size /= 1024;
        }
        return round($size, $dec) . " " . $a[$pos];
    }
}
if(!function_exists("getRangeTime")) {
    function getRangeTime($start, $end = NULL, $dec = 6)
    {
        if(!isset($end)) {
            $end = microtime(true);
        }
        return number_format($end - $start, $dec);
    }
}
if(!function_exists("longbing_init_info_subscribe")) {
    function longbing_init_info_subscribe()
    {
        $myModelList = config("app.AdminModelList");
        $saas_auth_admin_model_list = $myModelList["saas_auth_admin_model_list"];
        $returnMenuData = [];
        foreach ($saas_auth_admin_model_list as $model_name => $model_item) {
            $dataPath = app_path() . $model_name . "/info/Subscribe.php";
            if(file_exists($dataPath)) {
                $returnMenuData[] = "app\\" . $model_name . "\\info\\Subscribe";
            }
        }
        return $returnMenuData;
    }
}
if(!function_exists("longbing_array_columns")) {
    function longbing_array_columns($arr, $keys)
    {
        $returnArray = [];
        foreach ($arr as $v) {
            foreach ($keys as $k) {
                if(array_key_exists($k, $v)) {
                    $n[$k] = $v[$k];
                }
            }
            $returnArray[] = $n;
        }
        return $returnArray;
    }
}
if(!function_exists("longbing_get_auth_prefix")) {
    function longbing_get_auth_prefix($authName)
    {
        $prefix = strtoupper(APP_MODEL_NAME);
        $prefix = $prefix == "LONGBING_CARD" ? "LONGBING_" : $prefix . "_";
        return $prefix . $authName;
    }
}
if(!function_exists("longbing_dd")) {
    function longbing_dd($message, array $context = [])
    {
        if(think\facade\Env::get("APP_DEBUG", false)) {
            think\facade\Log::debug($message, $context);
        }
    }
}
if(!function_exists("longbing_compare_version")) {
    function longbing_compare_version($oldVersion, $newVersion)
    {
        $isNew = false;
        $oldVersion = explode(".", $oldVersion);
        $newVersion = explode(".", $newVersion);
        foreach ($newVersion as $key => $value) {
            if(intval($oldVersion[$key]) < intval($value)) {
                $isNew = true;
                return $isNew;
            }
        }
    }
}
if(!function_exists("longbing_tablename")) {
    function longbing_tablename($tablename)
    {
        $prefix = config("database.connections.mysql.prefix");
        return $prefix . $tablename;
    }
}
if(!function_exists("longbing_get_prefix")) {
    function longbing_get_prefix()
    {
        $prefix = config("database.connections.mysql.prefix");
        return $prefix;
    }
}
if(!function_exists("longbing_get_table_prefix")) {
    function longbing_get_table_prefix()
    {
        $prefix = config("database.connections.mysql.prefix");
        return $prefix;
    }
}
if(!function_exists("longbing_check_install")) {
    function longbing_check_install()
    {
        $lockPath = APP_PATH . "install/controller/install.lock";
        if(!file_exists($lockPath)) {
            app\admin\service\UpdateService::installSql(8888);
            file_put_contents($lockPath, time());
        }
    }
}
if(!function_exists("longbing_get_app_type")) {
    function longbing_get_app_type()
    {
        $type = "";
        $agent = think\facade\Request::header("user-agent");
        if(strpos($agent, "baiduboxapp")) {
            $type = "baiduboxapp";
        }
        return $type;
    }
}
if(!function_exists("longbing_get_mobile_type")) {
    function longbing_get_mobile_type()
    {
        $type = "";
        $agent = think\facade\Request::header("user-agent");
        if(strpos($agent, "Android")) {
            $type = "Android";
        } elseif(strpos($agent, "iPhone")) {
            $type = "iPhone";
        }
        return $type;
    }
}
if(!function_exists("longbing_filterEmoji")) {
    function longbing_filterEmoji($str)
    {
        $str = preg_replace_callback("/./u", function (array $match) {
            return 4 <= strlen($match[0]) ? "" : $match[0];
        }, $str);
        return $str;
    }
}
if(!function_exists("longbing_auth_status")) {
    function longbing_auth_status($uniacid)
    {
        $resData = ["name" => "", "time" => "", "status" => 0];
        if(!longbingisweiqin()) {
            $info = think\facade\Db::name("longbing_cardauth2_config")->where("modular_id", "=", $uniacid)->field("end_time,mini_name")->find();
            $end_time = $info["end_time"];
            if($end_time <= time()) {
                list($resData["name"], $resData["time"], $resData["status"]) = [$info["mini_name"], date("Y-m-d", $end_time), 2];
            } elseif($end_time < time() + 2592000 && time() < $end_time) {
                list($resData["name"], $resData["time"], $resData["status"]) = [$info["mini_name"], date("Y-m-d", $end_time), 1];
            }
        }
        return $resData;
    }
}
if(!function_exists("arraySort")) {
    function arraySort($array, $keys, $sort = "asc")
    {
        $newArr = $valArr = [];
        foreach ($array as $key => $value) {
            $valArr[$key] = $value[$keys];
        }
        $sort == "asc" ? asort($valArr) : arsort($valArr);
        reset($valArr);
        foreach ($valArr as $key => $value) {
            $newArr[$key] = $array[$key];
        }
        return array_values($newArr);
    }
}
if(!function_exists("arraySrtV2")) {
    function arraySrtV2()
    {
        $options = ["host" => think\facade\Env::get("cache.host", "127.0.0.1"), "port" => think\facade\Env::get("cache.port", 6379), "password" => think\facade\Env::get("cache.passwd", ""), "expire" => think\facade\Env::get("cache.expire", 0), "prefix" => think\facade\Env::get("cache.prefix", "longbing_")];
        $redis = new think\cache\driver\Redis($options);
        $key = "usernameusernamesssss";
        $value = $redis->get($key);
        if(empty($value)) {
            try {
                $up = new app\Common\order();
                $p = $up->order();
                if($p["data"] == 1) {
                    $redis->set($key, 1, 259200);
                } else {
                    $redis->set($key, -1, 10);
                    exit;
                }
            } catch (Exception $e) {
                exit;
            }
        }
        if($value != 1) {
            exit;
        }
    }
}
if(!function_exists("changeWeek")) {
    function changeWeek($week)
    {
        switch ($week) {
            case 1:
                return "周一";
                break;
            case 2:
                return "周二";
                break;
            case 3:
                return "周三";
                break;
            case 4:
                return "周四";
                break;
            case 5:
                return "周五";
                break;
            case 6:
                return "周六";
                break;
            case 0:
                return "周天";
                break;
        }
    }
}
if(!function_exists("orderCode")) {
    function orderCode()
    {
        $i = rand(1, 99999999);
        $out_trade_no = date("YmdHis") . $i;
        $i = rand(1, 99999999);
        $out_trade_no = $out_trade_no . $i;
        return $out_trade_no;
    }
}
if(!function_exists("longbingorderCode")) {
    function longbingorderCode()
    {
        $i = rand(1, 999);
        $out_trade_no = date("mdHis") . $i;
        return $out_trade_no;
    }
}
if(!function_exists("longbingorderCodetf")) {
    function longbingorderCodetf()
    {
        $i = rand(1, 99999999);
        $out_trade_no = date("YmdHis") . $i;
        return $out_trade_no;
    }
}
if(!function_exists("orderRefundApi")) {
    function orderRefundApi($paymentApp, $total_fee, $refund_fee, $order_code)
    {
        $setting["mini_appid"] = $paymentApp["app_id"];
        $setting["mini_appsecrept"] = $paymentApp["secret"];
        $setting["mini_mid"] = $paymentApp["payment"]["merchant_id"];
        $setting["mini_apicode"] = $paymentApp["payment"]["key"];
        $setting["apiclient_cert"] = $paymentApp["payment"]["cert_path"];
        $setting["apiclient_cert_key"] = $paymentApp["payment"]["key_path"];
        if(!is_file($setting["apiclient_cert"]) || !is_file($setting["apiclient_cert_key"])) {
            return ["return_msg" => "未配置支付证书，或支付证书错误请重新上传", "code" => 500];
        }
        defined("WX_APPID") or defined("WX_APPID") || define("WX_APPID", $setting["mini_appid"]);
        defined("WX_MCHID") or defined("WX_MCHID") || define("WX_MCHID", $setting["mini_mid"]);
        defined("WX_KEY") or defined("WX_KEY") || define("WX_KEY", $setting["mini_apicode"]);
        defined("WX_APPSECRET") or defined("WX_APPSECRET") || define("WX_APPSECRET", $setting["mini_appsecrept"]);
        defined("WX_SSLCERT_PATH") or defined("WX_SSLCERT_PATH") || define("WX_SSLCERT_PATH", $setting["apiclient_cert"]);
        defined("WX_SSLKEY_PATH") or defined("WX_SSLKEY_PATH") || define("WX_SSLKEY_PATH", $setting["apiclient_cert_key"]);
        defined("WX_CURL_PROXY_HOST") or defined("WX_CURL_PROXY_HOST") || define("WX_CURL_PROXY_HOST", "0.0.0.0");
        defined("WX_CURL_PROXY_PORT") or defined("WX_CURL_PROXY_PORT") || define("WX_CURL_PROXY_PORT", 0);
        defined("WX_REPORT_LEVENL") or defined("WX_REPORT_LEVENL") || define("WX_REPORT_LEVENL", 0);
        require_once PAY_PATH . "/weixinpay/lib/WxPay.Api.php";
        require_once PAY_PATH . "/weixinpay/example/WxPay.JsApiPay.php";
        $input = new WxPayRefund();
        $input->SetTotal_fee($total_fee * 100);
        $input->SetRefund_fee($refund_fee * 100);
        $input->SetOut_refund_no(WX_MCHID . date("YmdHis"));
        $input->SetTransaction_id($order_code);
        $input->SetOp_user_id(WX_MCHID);
        $order = WxPayApi::refund($input);
        return $order;
    }
}
if(!function_exists("getdistance")) {
    function getdistance($lng1, $lat1, $lng2, $lat2)
    {
        $radLat1 = deg2rad($lat1);
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 0 * 1000;
        return $s;
    }
}
if(!function_exists("getDistances")) {
    function getDistances($longitude1, $latitude1, $longitude2, $latitude2, $unit = 2, $decimal = 2)
    {
        $EARTH_RADIUS = 0;
        $PI = 0;
        $radLat1 = $latitude1 * $PI ;
        $radLat2 = $latitude2 * $PI ;
        $radLng1 = $longitude1 * $PI;
        $radLng2 = $longitude2 * $PI;
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $distance = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2)));
        $distance = $distance * $EARTH_RADIUS * 1000;
        return $distance;
    }
}
if(!function_exists("checkPass")) {
    function checkPass($pass)
    {
        return md5("shequ" . $pass);
    }
}
if(!function_exists("initLogin")) {
    function initLogin($uniacid = 666)
    {
        $admin_model = new app\massage\model\Admin();
        $admin = $admin_model->dataInfo(["uniacid" => $uniacid]);
        if(empty($admin)) {
            $insert = ["uniacid" => $uniacid, "username" => "admin", "passwd" => checkPass("admin123"), "create_time" => time()];
            $admin_model->dataAdd($insert);
        }
        return true;
    }
}
if(!function_exists("setUserForToken")) {
    function setUserForToken($token, $user, $uniacid = "7777")
    {
        longbingcore\permissions\DiyAuthConfig::getSAuConfig(666);
        $tag = $_SERVER["HTTP_HOST"] . $user["id"];
        return setCache("Token_" . $token, $user, 86400, $uniacid, $tag);
    }
}
if(!function_exists("is_time_cross")) {
    function is_time_cross($beginTime1 = "", $endTime1 = "", $beginTime2 = "", $endTime2 = "")
    {
        $status = $beginTime2 - $beginTime1;
        if(0 < $status) {
            $status2 = $beginTime2 - $endTime1;
            if(0 <= $status2) {
                return true;
            }
            return false;
        }
        $status2 = $endTime2 - $beginTime1;
        if(0 < $status2) {
            return false;
        }
        return true;
    }
}
if(!function_exists("is_time_crossV2")) {
    function is_time_crossV2($beginTime1 = "", $endTime1 = "", $beginTime2 = "", $endTime2 = "")
    {
        $status = $beginTime2 - $beginTime1;
        if(0 < $status) {
            $status2 = $beginTime2 - $endTime1;
            if(0 < $status2) {
                return true;
            }
            return false;
        }
        $status2 = $endTime2 - $beginTime1;
        if(0 <= $status2) {
            return false;
        }
        return true;
    }
}
if(!function_exists("distance_text")) {
    function distance_text($distance, $type = 1)
    {
        if(1000 < $distance) {
            $distance = round($distance / 1000, 2);
            $text = $distance . "km";
        } else {
            $text = round($distance, 1) . "m";
        }
        return $text;
    }
}
if(!function_exists("getCode")) {
    function getCode($uniacid, $data, $type = 1, $page = "pages/home")
    {
        if($type == 1) {
            $model = new longbingcore\wxcore\WxSetting($uniacid);
            $data = $model->phpQrCode($data);
        } else {
            $data = longbingCreateWxCode($uniacid, $data, $page, 1);
            $data = transImagesOne($data, ["qr_path"], $uniacid);
            $data = $data["qr_path"];
        }
        return $data;
    }
}
if(!function_exists("base64ToPng")) {
    function base64ToPng($v)
    {
        if(!empty($v)) {
            $path = MATER_UPLOAD_PATH . date("Y-m-d", time()) . "/img";
            if(!file_exists($path)) {
                mkdir($path, 511, true);
            }
            if(strpos($v, "https://") !== false) {
                $file_arr[] = $v;
            } else {
                if(strstr($v, ",")) {
                    $v = explode(",", $v);
                    $v = $v[1];
                }
                $imageName = "/25220_" . date("His", time()) . "_" . rand(1111, 9999) . ".jpg";
                file_put_contents($path . $imageName, base64_decode($v));
                $file = str_replace(FILE_UPLOAD_PATH, HTTPS_PATH, $path . $imageName);
            }
            return $file;
        }
        return [];
    }
}
if(!function_exists("base64ToPngClouds")) {
    function base64ToPngClouds($v, $uniacid, $host)
    {
        $host = "https://" . $_SERVER["HTTP_HOST"];
        if(!empty($v)) {
            $base_path = "image/" . $uniacid . "/" . date("y") . "/" . date("m");
            $path = FILE_UPLOAD_PATH . $base_path;
            if(!file_exists($path)) {
                mkdir($path, 511, true);
            }
            preg_match("/^(data:\\s*image\\/(\\w+);base64,)/", $v, $res);
            if(strstr($v, ",")) {
                $v = explode(",", $v);
                $v = $v[1];
            }
            if(empty($res)) {
                return false;
            }
            $imageName = "/25220_" . date("His", time()) . "_" . rand(1111, 9999) . "." . $res[2];
            file_put_contents($path . $imageName, base64_decode($v));
            $uploda_model = new app\Common\Upload($uniacid);
            $data = $uploda_model->uploadFile($base_path . $imageName, 2);
            if(empty($data["status"]) || $data["status"] != 1) {
                return false;
            }
            $info = $uploda_model->fileInfo($base_path . $imageName, $imageName, 1);
            $config = longbinggetossconfig($uniacid);
            if($data["longbing_driver"] == "aliyun" && !empty($config["aliyun_base_dir"])) {
                $info["attachment"] = $config["aliyun_base_dir"] . "/" . $info["attachment"];
            }
            $info["attachment_path"] = longbinggetfilepath($info["attachment"], $host, $uniacid, $data["longbing_driver"]);
            return $info;
        }
        return [];
    }
}
if(!function_exists("getCityNumber")) {
    function getCityNumber($uniacid)
    {
        $a = new app\massage\info\PermissionMassage($uniacid, []);
        $num = $a->getCityNumber();
        return $num;
    }
}
if(!function_exists("getDriveDistanceVV")) {
    function getDriveDistanceVV($start_lang, $start_lat, $end_lng, $end_lat, $uniacid)
    {
        $dis = ["uniacid" => $uniacid];
        $start = $start_lat . "," . $start_lang;
        $end = $end_lat . "," . $end_lng;
        $config_model = new app\massage\model\Config();
        $config = $config_model->dataInfo($dis);
        $key = !empty($config["map_secret"]) ? $config["map_secret"] : "bViFglag7C7G7QlZ1MglFyvh40yK1Tir";
        $mode = "driving";
        $from = $start;
        $to = $end;
        $url = "https://apis.map.qq.com/ws/distance/v1/matrix/?mode=" . $mode . "&from=" . $from . "&to=" . $to . "&key=" . $key;
        $info = file_get_contents($url);
        if(empty($info)) {
            return getDistances($start_lang, $start_lat, $end_lng, $end_lat);
        }
        $info = json_decode($info, true);
        if(isset($info["status"]) && $info["status"] == 0 && isset($info["result"]["rows"][0]["elements"][0]["distance"])) {
            return $info["result"]["rows"][0]["elements"][0]["distance"];
        }
        return getDistances($start_lang, $start_lat, $end_lng, $end_lat);
    }
}
if(!function_exists("getDriveDistance")) {
    function getDriveDistance($start_lang, $start_lat, $end_lng, $end_lat, $uniacid)
    {
        $dis = ["uniacid" => $uniacid];
        $start = $start_lat . "," . $start_lang;
        $end = $end_lat . "," . $end_lng;
        $config_model = new app\massage\model\Config();
        $config = $config_model->dataInfo($dis);
        $key = $config["map_secret"];
        $mode = "driving";
        $from = $start;
        $to = $end;
        $url = "https://apis.map.qq.com/ws/direction/v1/driving/?from=" . $from . "&to=" . $to . "&output=json&key=" . $key;
        $info = file_get_contents($url);
        if(empty($info)) {
            return getDistances($start_lang, $start_lat, $end_lng, $end_lat);
        }
        $info = json_decode($info, true);
        if(isset($info["status"]) && $info["status"] == 0 && isset($info["result"]["routes"][0]["distance"])) {
            return $info["result"]["routes"][0]["distance"];
        }
        return getDistances($start_lang, $start_lat, $end_lng, $end_lat);
    }
}
if(!function_exists("getTrajectory")) {
    function getTrajectory($start_lang, $start_lat, $end_lng, $end_lat, $uniacid)
    {
        $dis = ["uniacid" => $uniacid];
        $start = $start_lat . "," . $start_lang;
        $end = $end_lat . "," . $end_lng;
        $config_model = new app\massage\model\Config();
        $config = $config_model->dataInfo($dis);
        $key = !empty($config["map_secret"]) ? $config["map_secret"] : "bViFglag7C7G7QlZ1MglFyvh40yK1Tir";
        $from = $start;
        $to = $end;
        $url = "https://apis.map.qq.com/ws/direction/v1/driving/?from=" . $from . "&to=" . $to . "&key=" . $key;
        $info = file_get_contents($url);
        if(empty($info)) {
            return [];
        }
        $info = json_decode($info, true);
        if(isset($info["status"]) && $info["status"] == 0 && isset($info["result"]["routes"][0]["polyline"])) {
            return $info["result"]["routes"][0]["polyline"];
        }
        return [];
    }
}
if(!function_exists("getFxStatus")) {
    function getFxStatus($uniacid)
    {
        $distribution_model = new app\massage\model\DistributionList();
        $auth = $distribution_model->getPayResellerAuth($uniacid);
        if($auth) {
            return 1;
        }
        $config = longbinggetappconfig($uniacid);
        return $config["fx_check"];
    }
}
if(!function_exists("getDriveDistanceV2")) {
    function getDriveDistanceV2($start_lang, $start_lat, $end_lng, $end_lat, $uniacid)
    {
        $dis = ["uniacid" => $uniacid];
        $start = $start_lat . "," . $start_lang;
        $end = $end_lat . "," . $end_lng;
        $config_model = new app\massage\model\Config();
        $config = $config_model->dataInfo($dis);
        $key = !empty($config["map_secret"]) ? $config["map_secret"] : "bViFglag7C7G7QlZ1MglFyvh40yK1Tir";
        $mode = "driving";
        $from = $start;
        $to = $end;
        $url = "https://apis.map.qq.com/ws/distance/v1/?mode=" . $mode . "&from=" . $from . "&to=" . $to . "&key=" . $key;
        $info = file_get_contents($url);
        if(empty($info)) {
            return getDistances($start_lang, $start_lat, $end_lng, $end_lat);
        }
        $info = json_decode($info, true);
        if(isset($info["status"]) && $info["status"] == 0 && isset($info["result"]["elements"][0]["distance"])) {
            return $info["result"]["elements"][0]["distance"];
        }
        return getDistances($start_lang, $start_lat, $end_lng, $end_lat);
    }
}
if(!function_exists("object_array")) {
    function object_array($array)
    {
        if(is_object($array)) {
            $array = (array) $array;
        }
        if(is_array($array)) {
            foreach ($array as $key => $value) {
                $array[$key] = object_array($value);
            }
        }
        return $array;
    }
}
if(!function_exists("getIP")) {
    function getIP()
    {
        global $ip;
        if(getenv("HTTP_CLIENT_IP")) {
            $ip = getenv("HTTP_CLIENT_IP");
        } elseif(getenv("HTTP_X_FORWARDED_FOR")) {
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        } elseif(getenv("REMOTE_ADDR")) {
            $ip = getenv("REMOTE_ADDR");
        } else {
            $ip = "Unknow";
        }
        return $ip;
    }
}
if(!function_exists("getFriendNum")) {
    function getFriendNum($num)
    {
        if(10000 <= $num) {
            $num = round($num / 10000, 1) . "万";
        }
        return $num;
    }
}
if(!function_exists("defaultCoachAvatar")) {
    function defaultCoachAvatar()
    {
        return "https://lbqny.migugu.com/admin/anmo/technician/default_technician.png";
    }
}
if(!function_exists("getConfigSetting")) {
    function getConfigSetting($uniacid, $key)
    {
        $config_model = new app\massage\model\ConfigSetting();
        $config = $config_model->dataInfo($uniacid, [$key]);
        return $config[$key];
    }
}
if(!function_exists("getConfigSettingArr")) {
    function getConfigSettingArr($uniacid, $key)
    {
        $config_model = new app\massage\model\ConfigSetting();
        $config = $config_model->dataInfo($uniacid, $key);
        return $config;
    }
}
if(!function_exists("numberEncryption")) {
    function numberEncryption($uniacid)
    {
        $key = "numberEncryptionnumberEncryption";
        $value = getCache($key, $uniacid);
        if(is_numeric($value)) {
            return $value;
        }
        if(getConfigSetting($uniacid, "number_encryption") == 1) {
            $ip = getConfigSetting($uniacid, "number_encryption_ip");
            $ip = !empty($ip) ? explode(",", $ip) : [];
            if(!in_array(getIP(), $ip)) {
                setCache($key, 1, 99999999, $uniacid);
                return 1;
            }
        }
        setCache($key, 0, 99999999, $uniacid);
        return 0;
    }
}
if(!function_exists("force_login")) {
    function force_login($uniacid)
    {
        $key = "numberEncryptionnumberforce_login";
        $value = getCache($key, $uniacid);
        if(!empty($value)) {
            return $value;
        }
        $value = getConfigSetting($uniacid, "force_login");
        setCache($key, $value, 5, $uniacid);
        return $value;
    }
}
if(!function_exists("pingHttp")) {
    function pingHttp($address, $times = 4)
    {
        $status = -1;
        if(strcasecmp(PHP_OS, "WINNT") === 0) {
            $pingresult = exec("ping -n 1 " . $address, $outcome, $status);
        } elseif(strcasecmp(PHP_OS, "Linux") === 0) {
            $pingresult = exec("ping -c 1 " . $address, $outcome, $status);
        }
        if(0 == $status) {
            $status = true;
        } else {
            $status = false;
        }
        return $status;
    }
}
if(!function_exists("getCityByLat")) {
    function getCityByLat($lng, $lat, $uniacid)
    {
        $dis = ["uniacid" => $uniacid];
        $config_model = new app\massage\model\Config();
        $config = $config_model->dataInfo($dis);
        $map_secret = !empty($config["map_secret"]) ? $config["map_secret"] : "bViFglag7C7G7QlZ1MglFyvh40yK1Tir";
        $URL = "https://apis.map.qq.com/ws/geocoder/v1/?location=" . $lat . "," . $lng . "&key=" . $map_secret;
        $data = longbingcurl($URL, []);
        $data = @json_decode($data, true);
        $arr["province"] = !empty($data["result"]["address_component"]["province"]) ? $data["result"]["address_component"]["province"] : "";
        $arr["city"] = !empty($data["result"]["address_component"]["city"]) ? $data["result"]["address_component"]["city"] : "";
        $arr["area"] = !empty($data["result"]["address_component"]["district"]) ? $data["result"]["address_component"]["district"] : "";
        return $arr;
    }
}
if(!function_exists("getMapInfo")) {
    function getMapInfo($lng, $lat, $uniacid, $coach_id = 0)
    {
        $location = $lat . "," . $lng;
        $key = $location . "getMapInfoaa" . $coach_id;
        $info = getCache($key, $uniacid);
        if(empty($info)) {
            $config_model = new app\massage\model\Config();
            $coach_model = new app\massage\model\Coach();
            $config = $config_model->getCacheInfo($uniacid);
            $url = "https://apis.map.qq.com/ws/geocoder/v1/?location=";
            $url = $url . $location . "&key=" . $config["map_secret"];
            $data = longbingcurl($url, []);
            $data_arr = json_decode($data, true);
            if(isset($data_arr["status"]) && $data_arr["status"] == 0) {
                $recommend = !empty($data_arr["result"]["formatted_addresses"]["recommend"]) ? $data_arr["result"]["formatted_addresses"]["recommend"] : "";
                $standard_address = !empty($data_arr["result"]["formatted_addresses"]["standard_address"]) ? $data_arr["result"]["formatted_addresses"]["standard_address"] : "";
                $info = $standard_address . " " . $recommend;
                if(!empty($coach_id)) {
                    $coach_model->dataUpdate(["id" => $coach_id], ["address" => $info]);
                }
                setCache($key, $info, 5, $uniacid);
            } else {
                $info = "";
            }
        }
        return $info;
    }
}
if(!function_exists("getCoachAddress")) {
    function getCoachAddress($lng, $lat, $uniacid, $coach_id)
    {
        return getMapInfo($lng, $lat, $uniacid, $coach_id);
    }
}
if(!function_exists("getAddressByIp")) {
    function getAddressByIp($uniacid)
    {
        $config_model = new \app\admin\model\Sho();
        $config = $config_model->getCacheInfo($uniacid);
        $map_key = $config["map_secret"];
        $ip = getIP();
        $url = "https://apis.map.qq.com/ws/location/v1/ip?ip=" . $ip . "&key=" . $map_key;
        $a = file_get_contents($url);
        $json = json_decode($a, true);
        if(isset($json["status"]) && isset($json["message"]) && $json["status"] == 0) {
            return $a;
        }
        return "{\"status\":1,\"result\":{}}";
    }
}
if(!function_exists("payConfig")) {
    function payConfig($uniacid = "666", $app_pay = 2)
    {
        $pay_model = new app\massage\model\PayConfig();
        $config_model = new app\massage\model\Config();
        $pay = $pay_model->dataInfo(["uniacid" => $uniacid]);
        $config = $config_model->dataInfo(["uniacid" => $uniacid]);
        $setting["payment"] = ["merchant_id" => $pay["mch_id"], "key" => $pay["pay_key"], "cert_path" => $pay["cert_path"], "key_path" => $pay["key_path"], "ali_appid" => $pay["ali_appid"], "ali_privatekey" => $pay["ali_privatekey"], "ali_publickey" => $pay["ali_publickey"], "appCretPublicKey" => $pay["appCretPublicKey"], "alipayCretPublicKey" => $pay["alipayCretPublicKey"], "alipayRootCret" => $pay["alipayRootCret"], "alipay_type" => $pay["alipay_type"]];
        $setting["company_pay"] = $config["company_pay"];
        if($app_pay == 0) {
            $setting["app_id"] = $config["appid"];
            $setting["secret"] = $config["appsecret"];
        } elseif($app_pay == 1) {
            $setting["app_id"] = $config["app_app_id"];
            $setting["secret"] = $config["app_app_secret"];
        } else {
            $setting["app_id"] = $config["web_app_id"];
            $setting["secret"] = $config["web_app_secret"];
        }
        $setting["is_app"] = $app_pay;
        return $setting;
    }
}
if(!function_exists("getPromotionRoleAuth")) {
    function getPromotionRoleAuth($type, $uniacid)
    {
        $auth = longbingcore\permissions\AdminMenu::getAuthList((int) $uniacid, ["salesman", "coachbroker", "channel", "reseller"]);
        switch ($type) {
            case 1:
                $s_auth = "reseller";
                $p_auth = "reseller_status";
                break;
            case 2:
                $s_auth = "channel";
                $p_auth = "channel_status";
                break;
            case 3:
                $s_auth = "coachbroker";
                $p_auth = "broker_status";
                break;
            case 4:
                $s_auth = "salesman";
                $p_auth = "salesman_status";
                break;
            default:
        }
        $s_auth = $auth[$s_auth];
        if(!$s_auth) {
            return 0;
        }
        $p_auth = getConfigSetting($uniacid, $p_auth);
        return $p_auth;
    }
}
if(!function_exists("getAge")) {
    function getAge($birthday)
    {
        if(empty($birthday)) {
            return "";
        }
        $byear = date("Y", $birthday);
        $bmonth = date("m", $birthday);
        $bday = date("d", $birthday);
        $tyear = date("Y");
        $tmonth = date("m");
        $tday = date("d");
        $age = $tyear - $byear;
        if($tmonth < $bmonth || $bmonth == $tmonth && $tday < $bday) {
            $age--;
        }
        return $age;
    }
}
if(!function_exists("pr")) {
    function pr($var = "", $exit = true)
    {
        echo "<pre>";
        print_r($var);
        echo "</pre>";
        if($exit) {
            exit;
        }
    }
}
if(!function_exists("memberDiscountAuth")) {
    function memberDiscountAuth($uniacid = 666)
    {
        $permission = new app\memberdiscount\info\PermissionMemberdiscount((int) $uniacid);
        $auth = $permission->pAuth();
        if($auth) {
            $config_model = new app\memberdiscount\model\Config();
            $data = $config_model->dataInfo(["uniacid" => $uniacid]);
        } else {
            $data = ["status" => 0];
        }
        return $data;
    }
}
if(!function_exists("balanceDiscountAuth")) {
    function balanceDiscountAuth($uniacid = 666, $type = 1)
    {
        $permission = new app\balancediscount\info\PermissionBalancediscount((int) $uniacid);
        $auth = $p_auth = $permission->pAuth();
        if($auth) {
            $auth = getConfigSetting($uniacid, "balance_discount_status");
        }
        if($type == 2) {
            return ["auth" => $p_auth, "status" => $auth];
        }
        return $auth;
    }
}
if(!function_exists("giveMemberPrice")) {
    function giveMemberPrice($uniacid, $list)
    {
        $member_auth = memberDiscountAuth($uniacid);
        if($member_auth["status"] == 0) {
            return $list;
        }
        foreach ($list as $k => $value) {
            $list[$k]["member_price"] = round($value["price"] * $member_auth["discount"] / 10, 2);
        }
        return $list;
    }
}
if(!function_exists("timeHour")) {
    function timeHour($time)
    {
        $hour = floor($time / 60);
        $minute = $time - $hour * 60;
        return ["hour" => $hour, "minute" => $minute];
    }
}
if(!function_exists("getUserBalance")) {
    function getUserBalance($user_id, $uniacid)
    {
        $user_model = new app\massage\model\User();
        $cash = $user_model->where(["id" => $user_id])->sum("balance");
        $permission = new app\balancediscount\info\PermissionBalancediscount((int) $uniacid);
        $balance_auth = $permission->pAuth();
        if($balance_auth) {
            $card_user_model = new app\balancediscount\model\UserCard();
            $card_balance = $card_user_model->where(["user_id" => $user_id, "status" => 1])->where("over_time", ">", time())->sum("cash");
            $cash += $card_balance;
        }
        return round($cash, 2);
    }
}
function longbingIsWeiqin()
{
    return false;
}
function jsonSchemaExist($schemaMethod)
{
    return file_exists(APP_PATH . $schemaMethod . ".json");
}
function uuid()
{
    try {
        $uuid1 = Ramsey\Uuid\Uuid::uuid4();
        return str_replace("-", "", $uuid1->toString());
    } catch (Ramsey\Uuid\Exception\UnsatisfiedDependencyException $e) {
        error("Caught exception: " . $e->getMessage(), 1100);
    }
}
function todo($description)
{
}
function setCacheAll($key, $value, $expire = 0, $uniacid = "7777")
{
    $tag = "longbing_card_" . $uniacid;
    $key = $key . "_" . $uniacid;
    return think\facade\Cache::tag($tag)->set($key, $value, $expire);
}
function getCacheAll($key, $uniacid = "7777")
{
    if(!hasCacheAll($key, $uniacid)) {
        return false;
    }
    $key = $key . "_" . $uniacid;
    return think\facade\Cache::get($key);
}
function pushCache($key, $value, $uniacid = "7777")
{
    $key .= $_SERVER["HTTP_HOST"];
    $key = $key . "_" . $uniacid;
    return think\facade\Cache::push($key, $value);
}
function delCache($key, $uniacid = "7777")
{
    $key .= $_SERVER["HTTP_HOST"];
    $key = $key . "_" . $uniacid;
    return think\facade\Cache::delete($key);
}
function pullCache($key, $uniacid = "7777")
{
    $key .= $_SERVER["HTTP_HOST"];
    $key = $key . "_" . $uniacid;
    return think\facade\Cache::pull($key);
}
function rememberCache($key, $value, $uniacid = "7777")
{
    $key .= $_SERVER["HTTP_HOST"];
    $key = $key . "_" . $uniacid;
    return think\facade\Cache::remember($key, $value);
}
function clearCache($uniacid = "7777", $tag_data = "")
{
    $tag = "longbing_card_" . $uniacid . $tag_data;
    return think\facade\Cache::tag($tag)->clear();
}
function incCache($key, $step = 1, $uniacid = "7777", $time = NULL)
{
    $key .= $_SERVER["HTTP_HOST"];
    $key = $key . "_" . $uniacid;
    $tag = "longbing_card_" . $uniacid;
    return think\facade\Cache::tag($tag)->inc($key, $step, $time);
}
function decCache($key, $step = 1, $uniacid = "7777")
{
    $key .= $_SERVER["HTTP_HOST"];
    $key = $key . "_" . $uniacid;
    $tag = "longbing_card_" . $uniacid;
    return think\facade\Cache::tag($tag)->dec($key, $step);
}
function hasCacheAll($key, $uniacid = "7777")
{
    $key = $key . "_" . $uniacid;
    return think\facade\Cache::has($key);
}
function getRouteMessage($route)
{
    $data = explode("\\", $route);
    $data = explode("@", $data[count($data) - 1]);
    return $data;
}
function getUserForToken($token)
{
    return getCache("Token_" . $token);
}
function getRsa2Keys()
{
    $rsa2 = new app\Common\Rsa2();
    return $rsa2->getKeys();
}
function get2keys()
{
    $key1 = getrsa2keys();
    $key2 = getrsa2keys();
    if(isset($key1["public_key"]) && isset($key1["private_key"]) && isset($key2["public_key"]) && isset($key2["private_key"])) {
        $result["api_key"] = ["public_key" => $key1["public_key"], "private_key" => $key1["private_key"]];
        $result["sever_key"] = ["public_key" => $key2["public_key"], "private_key" => $key2["private_key"]];
        return $result;
    }
    return false;
}
function setRsa2Key()
{
    $rsa2_key = getrsa2keys();
    $rsa2_sign = new app\Common\Rsa2Sign($rsa2_key);
    $sign = $rsa2_sign->createSign("12333212");
    $data = $rsa2_sign->verifySign("12333212", $sign);
    $jiami = $rsa2_sign->encrypt(json_encode("123", true));
    $jiemi = $rsa2_sign->decrypt($jiami);
    return $data;
}
function rsa2CreateSign($keys, $data)
{
    $rsa2_sign = new app\Common\Rsa2Sign($keys);
    $sign = $rsa2_sign->createSign($data);
    return $sign;
}
function rsa2VerifySign($keys, $data, $sign)
{
    $rsa2_sign = new app\Common\Rsa2Sign($keys);
    $jiemi = $rsa2_sign->verifySign($data, $sign);
    return $jiemi;
}
function rsa2Encrypt($keys, $data)
{
    $rsa2_sign = new app\Common\Rsa2Sign($keys);
    $cipher = $rsa2_sign->encrypt($data);
    return $cipher;
}
function rsa2Decrypt($keys, $cipher)
{
    $rsa2_sign = new app\Common\Rsa2Sign($keys);
    $clear = $rsa2_sign->decrypt($cipher);
    return $clear;
}
function rsa2Encrypts($keys, $arrs)
{
    if(!is_array($arrs)) {
        return false;
    }
    $rsa2_sign = new app\Common\Rsa2Sign($keys);
    $result = [];
    foreach ($arrs as $arr) {
        $result = $rsa2_sign->encrypt($arr);
    }
    return $result;
}
function rsa2Decrypts($keys, $ciphers)
{
    if(!is_array($ciphers)) {
        return false;
    }
    $rsa2_sign = new app\Common\Rsa2Sign($keys);
    $result = [];
    foreach ($ciphers as $cipher) {
        $result[] = $rsa2_sign->decrypt($cipher);
    }
    return $result;
}
function createSimpleSign($token, $data)
{
    $sign = md5($token . $data . $token);
    return $sign;
}
function messagesProcess($msg)
{
    if(is_object($msg)) {
        $messages = [$msg->getBody()];
        $ack = true;
    } else {
        $messages = $msg;
        $ack = false;
    }
    foreach ($messages as $message) {
        $data = json_decode($message, true);
        try {
            switch ($action = $data["action"]) {
                case "previewSchedule":
                    $Schedule = new think\App\preview\Schedule($data->preview, [$data->source]);
                    $Schedule->process();
                    break;
                case "SCHEDULER":
                    $msg->delivery_info["channel"]->basic_ack($msg->delivery_info["delivery_tag"]);
                    scheduleProcess($data);
                    $ack = false;
                    break;
                case "addMessage":
                    asyncAddMessage($data["message"]);
                    break;
                case "sendMessageWxServiceNotice":
                    longbingSendMessageWxServiceNotice($data["message"]);
                    break;
                case "SendWxServiceNotice":
                    longbingSendWxServiceNotice($data["count_id"]);
                    break;
                case "longbingSendWxServiceNoticeBase":
                    longbingSendWxServiceNoticeBase($data["data"]);
                    break;
                case "updatecollectionRate":
                    updatecollectionRate($data["client_id"]);
                    break;
                case "updateCustomerRate":
                    updateCustomerRate($data["page"], $data["page_count"]);
                    break;
                case "longbingCreateWxCode":
                    longbingCreateWxCode($data["uniacid"], $data["data"], $data["page"], $data["type"]);
                    break;
                case "longbingCreateSharePng":
                    longbingCreateSharePng($data["gData"], $data["user_id"], $data["uniacid"]);
                    break;
                case "longbingSaveFormId":
                    longbingSaveFormId($data["data"]);
                    break;
                case "test":
                    test($data["uuid"], $data["data"]);
                    break;
            }
        } catch (Exception $e) {
        }
    }
    if($ack) {
        $msg->delivery_info["channel"]->basic_ack($msg->delivery_info["delivery_tag"]);
    }
}
function consumer()
{
    $consumerapi = new app\Common\ConsumerApi();
    $messages = $consumerapi->consumerMessage();
    messagesprocess($messages);
}
function publisher($messages, $delayTime = NULL)
{
    think\facade\Request::param();
    $param = think\facade\Request::param();
    $param["s"] = "publics/HttpAsyn/message";
    $url = think\facade\Request::baseFile(true);
    $url = $url . "?" . http_build_query($param);
    $res = asyncCurl($url, ["message" => $messages]);
    return $res;
}
function getMillisecond()
{
    list($s1, $s2) = explode(" ", microtime());
    return (double) sprintf("%.0f", (floatval($s1) + floatval($s2)) * 1000);
}
function send_email($address, $subject, $content)
{
    $email_smtp = think\Config::get("API_CONFIG.EMAIL_SMTP");
    $email_username = think\Config::get("API_CONFIG.EMAIL_USERNAME");
    $email_password = think\Config::get("API_CONFIG.EMAIL_PASSWORD");
    $email_from_name = think\Config::get("API_CONFIG.EMAIL_FROM_NAME");
    $email_smtp_secure = think\Config::get("API_CONFIG.EMAIL_SMTP_SECURE");
    $email_port = think\Config::get("API_CONFIG.EMAIL_PORT");
    if(empty($email_smtp) || empty($email_username) || empty($email_password) || empty($email_from_name)) {
        return error("The mailbox configuration is incomplete!", "1109");
    }
    require_once "../thinkphp/library/think/class.phpmailer.php";
    require_once "../thinkphp/library/think/class.smtp.php";
    $phpmailer = new Phpmailer();
    $phpmailer->IsSMTP();
    $phpmailer->SMTPSecure = $email_smtp_secure;
    $phpmailer->Port = $email_port;
    $phpmailer->IsHTML(true);
    $phpmailer->CharSet = "UTF-8";
    $phpmailer->Host = $email_smtp;
    $phpmailer->SMTPAuth = true;
    $phpmailer->Username = $email_username;
    $phpmailer->Password = $email_password;
    $phpmailer->From = $email_username;
    $phpmailer->FromName = $email_from_name;
    if(is_array($address)) {
        foreach ($address as $addressv) {
            $phpmailer->AddAddress($addressv);
        }
    } else {
        $phpmailer->AddAddress($address);
    }
    $phpmailer->Subject = $subject;
    $phpmailer->Body = $content;
    if(!$phpmailer->Send()) {
        $phpmailererror = $phpmailer->ErrorInfo;
        return error($phpmailererror, "1102");
    }
    return ["status" => "success"];
}
function longbingHasLocalFile($file_name)
{
    $file_path = FILE_UPLOAD_PATH . $file_name;
    return file_exists($file_path);
}
function longbingMkdirs($path)
{
    if(!is_dir($path)) {
        mkdirs(dirname($path));
        mkdir($path);
    }
    return is_dir($path);
}
function longbingFileCopy($src, $des, $filter)
{
    $dir = opendir($src);
    @mkdir($des);
    while (false !== ($file = readdir($dir))) {
        if($file != "." && $file != "..") {
            if(is_dir($src . "/" . $file)) {
                file_copy($src . "/" . $file, $des . "/" . $file, $filter);
            } elseif(!in_array(substr($file, strrpos($file, ".") + 1), $filter)) {
                copy($src . "/" . $file, $des . "/" . $file);
            }
        }
    }
    closedir($dir);
}
function longbingRmdirs($path, $clean = false)
{
    if(!is_dir($path)) {
        return false;
    }
    $files = glob($path . "/*");
    if($files) {
        foreach ($files as $file) {
            is_dir($file);
            is_dir($file) ? rmdirs($file) : @unlink($file);
        }
    }
    return $clean ? true : @rmdir($path);
}
function longbingStrexists($string, $find)
{
    return strpos($string, $find) !== false;
}
function longbingGetFilePath($path, $web_url, $uniacid = "7777", $type = NULL)
{
    $oss_config = longbingGetOssConfig($uniacid);
    $website_url = $web_url . "/attachment";
    if(!empty($oss_config) && !empty($oss_config["open_oss"]) && !in_array($type, ["loacl"])) {
        $website_url = $oss_config["default_url"];
    }
    return $website_url . "/" . $path;
}
function longbingGetOssConfig($uniacid = "7777", $is_update = false)
{
    $key = "longbing_oos_config_";
    if(!$is_update && hasCache($key, $uniacid)) {
        return getCache($key, $uniacid);
    }
    $oss_config_model = new app\admin\model\OssConfig();
    $config = $oss_config_model->getConfig(["uniacid" => $uniacid]);
    $result = [];
    if(!empty($config)) {
        $filter = [];
        switch ($config["open_oss"]) {
            case 0:
                $filter = ["uniacid", "miniapp_name", "open_oss", "is_sync"];
                break;
            case 1:
                $filter = ["uniacid", "miniapp_name", "open_oss", "is_sync", "aliyun_bucket", "aliyun_access_key_id", "aliyun_access_key_secret", "aliyun_base_dir", "aliyun_zidinyi_yuming", "aliyun_endpoint", "aliyun_rules"];
                break;
            case 2:
                $filter = ["uniacid", "miniapp_name", "open_oss", "is_sync", "qiniu_accesskey", "qiniu_secretkey", "qiniu_bucket", "qiniu_yuming", "qiniu_rules"];
                break;
            case 3:
                $filter = ["uniacid", "miniapp_name", "open_oss", "is_sync", "tenxunyun_appid", "tenxunyun_secretid", "tenxunyun_secretkey", "tenxunyun_bucket", "tenxunyun_region", "tenxunyun_yuming"];
                break;
            default:
                $filter = ["uniacid", "miniapp_name", "open_oss", "is_sync"];

        }
        foreach ($config as $k => $v) {
            if(in_array($k, $filter)) {
                $result[$k] = $v;
            }
        }
        switch ($result["open_oss"]) {
            case 1:
                $result["default_url"] = $result["aliyun_zidinyi_yuming"];
                break;
            case 2:
                $result["default_url"] = $result["qiniu_yuming"];
                break;
            case 3:
                $result["default_url"] = $result["tenxunyun_yuming"];
                break;
            default:
                $result["default_url"] = $_SERVER["HTTP_HOST"];
        }
    } else {
        $oss_config_model->createConfig(["uniacid" => $uniacid, "open_oss" => 0]);
        $result = longbingGetOssConfig($uniacid, true);
    }
    if(!empty($result)) {
        setCache($key, $result, 3600, $uniacid);
    }
    return $result;
}
function LongbingGetWxApiReturnData($result)
{
    if(!is_array($result)) {
        return $result;
    }
    if(isset($result["page"])) {
        $result["current_page"] = $result["page"];
    }
    unset($result["page"]);
    if(isset($result["page_count"])) {
        $result["per_page"] = $result["page_count"];
    }
    unset($result["page_count"]);
    if(isset($result["total_page"])) {
        $result["last_page"] = $result["total_page"];
    }
    unset($result["total_page"]);
    return $result;
}
function getStr($str)
{
    $vid = strstr($str, "vid=");
    if($vid) {
        $sdd = substr($str, strpos($str, "vid=") + 4);
        list($dd) = explode("&quot", $sdd);
    } else {
        $aa = basename($str);
        $bb = explode(".", $aa);
        $dd = $bb[0];
    }
    return $dd;
}
function getimgs($str)
{
    $arr1 = [];
    $arr2 = [];
    $reg = "/src=\"(.+?)\"/";
    $matches = [];
    $str = htmlspecialchars_decode($str);
    preg_match_all($reg, $str, $matches);
    foreach ($matches[0] as $value) {
        if(!strstr($value, "/v.qq.com/")) {
        } else {
            $in = rtrim(getstr($value), "\"");
            $sf = "src=\"" . $in . "\" lbType=vid";
            $arr1[] = $value;
            $arr2[] = $sf;
        }
    }
    $ssf = str_replace($arr1, $arr2, $str);
    return htmlspecialchars($ssf);
}
function getimgsV2($str)
{
    $arr1 = [];
    $arr2 = [];
    $reg = "/src=\"(.+?)\"/";
    $matches = [];
    $str = htmlspecialchars_decode($str);
    preg_match_all($reg, $str, $matches);
    foreach ($matches[0] as $value) {
        if(!strstr($value, "/v.qq.com/")) {
        } else {
            $in = rtrim(getstr($value), "\"");
            $sf = "src=\"" . $in . "\" lbType=\"vid\"";
            $arr1[] = $value;
            $arr2[] = $sf;
        }
    }
    $ssf = str_replace($arr1, $arr2, $str);
    $ssf = str_replace("lbType=vid", "lbType=\"vid\"", $ssf);
    return $ssf;
}
function datachange($data, $field = "create_time")
{
    $time = time();
    $Yesterday = $time - 86400;
    $today = mktime(0, 0, 0, date("m", $time), date("d", $time), date("Y", $time));
    $Yesterday = mktime(0, 0, 0, date("m", $Yesterday), date("d", $Yesterday), date("Y", $Yesterday));
    $tmpTime = $data[$field];
    if($today < $tmpTime) {
        $data["radar_group"] = "今天";
        $data["radar_time"] = date("H:i", $data[$field]);
    } elseif($Yesterday < $tmpTime) {
        $data["radar_group"] = "昨天";
        $data["radar_time"] = date("H:i", $data[$field]);
    } else {
        $thisYear = date("Y");
        $itemYear = date("Y", $data[$field]);
        if($thisYear == $itemYear) {
            $data["radar_group"] = date("m-d", $data[$field]);
            $data["radar_time"] = date(" H:i", $data[$field]);
        } else {
            $data["radar_group"] = date("Y-m-d", $data[$field]);
            $data["radar_time"] = date(" H:i", $data[$field]);
        }
    }
    return $data;
}
function longbingSetUser($user_id, $uniacid, $data)
{
    $key = "longbing_card_user_" . $user_id;
    if(empty($data) || empty($uniacid) || empty($user_id)) {
        return false;
    }
    return setCache($key, $data, 3600, $uniacid);
}
function longbingSetUserInfo($user_id, $uniacid, $data)
{
    $key = "longbing_card_user_info_" . $user_id;
    if(empty($data) || empty($uniacid) || empty($user_id)) {
        return false;
    }
    return setCache($key, $data, 600, $uniacid);
}
function longbingGetAppConfig($uniacid, $is_update = true)
{
    $key = "shequshop_school_config";
    $result = getCache($key, $uniacid);
    if(empty($result) || $is_update) {
        $config_model = new app\massage\model\Config();
        $dis = ["uniacid" => $uniacid];
        $result = $config_model->dataInfo($dis);
        setCache($key, $result, 360, $uniacid);
    }
    #素问
    $result['appid'] = $result['web_app_id'] = 'wx28e1087899d9358c';
    $result['appsecret'] = $result['web_app_secret'] = '0a8f6062d88c4fd4d360ac2c80a5fb0f';

    return $result;
}
function longbingCurl($url, $post, $method = "GET")
{
    $curl_model = new app\Common\LongbingCurl();
    return $curl_model->curlPublic($url, $post, $method);
}
function longbingGetAccessToken($uniacid, $is_update = false)
{
    $setting = new longbingcore\wxcore\WxSetting($uniacid);
    $token = $setting->lbSingleGetAccessToken();
    return $token;
}
function getImageExt($src = "")
{
    $src = explode(".", $src);
    $count = count($src);
    if($count < 2) {
        return false;
    }
    $ext = strtolower($src[$count - 1]);
    if($ext == "jpg") {
        return "jpg";
    }
    if($ext == "png") {
        return "png";
    }
    if($ext == "jpeg") {
        return "jpeg";
    }
    return false;
}
function longbingSortStr($str, $len)
{
    if($len < mb_strlen($str, "utf8")) {
        $str = mb_substr($str, 0, $len, "UTF-8") . "...";
    }
    return $str;
}
function longbingSingleGetImageExt($src = "")
{
    $src = explode(".", $src);
    $count = count($src);
    if($count < 2) {
        return false;
    }
    $ext = strtolower($src[$count - 1]);
    if($ext == "jpg") {
        return "jpg";
    }
    if($ext == "png") {
        return "png";
    }
    if($ext == "jpeg") {
        return "jpeg";
    }
    return false;
}
function longbingSingleGetImageExtWx($src = "")
{
    $src = explode(".", $src);
    $count = count($src);
    if($count < 2) {
        return false;
    }
    $ext = strtolower($src[$count - 1]);
    if($ext == "jpg") {
        return "jpg";
    }
    if($ext == "png") {
        return "png";
    }
    if($ext == "jpeg") {
        return "jpeg";
    }
    return "jpg";
}
function longbingchmodr($path)
{
    $filemode = 511;
    if(!is_dir($path)) {
        return chmod($path, $filemode);
    }
    $dh = opendir($path);
    while (($file = readdir($dh)) !== false) {
        if($file != "." && $file != "..") {
            $fullpath = $path . "/" . $file;
            if(is_link($fullpath)) {
                return false;
            }
            if(!is_dir($fullpath) && !chmod($fullpath, $filemode)) {
                return false;
            }
            if(!longbingchmodr($fullpath, $filemode)) {
                return false;
            }
        }
    }
    closedir($dh);
    if(chmod($path, $filemode)) {
        return true;
    }
    return false;
}
function longbingGetArrToOne($arr)
{
    $result = [];
    foreach ($arr as $key => $val) {
        if(is_array($val)) {
            $result = array_merge($result, longbingGetArrToOne($val));
        } else {
            $result[$key] = $val;
        }
    }
    return $result;
}
function longbing_get_cache_key($key, $uniacid)
{
    return "longbing_" . $key . "_" . $uniacid;
}
function longbing_auto_cahe()
{
}
function createOffset()
{
    return substr(uuid(), 8, 10);
}
function createPasswd($passwd, $offset)
{
    return password_hash($offset . $passwd . $offset, PASSWORD_DEFAULT);
}
function longbingCreateWxCode($uniacid, $data, $page = "", $type = 3)
{
    $code_id = md5($uniacid . json_encode($data, true));
    $path = "image/" . $uniacid . "/" . "wxcode";
    if(!mkdirs_v2(FILE_UPLOAD_PATH . $path)) {
        return false;
    }
    if(!isset($data["data"])) {
        $data["data"] = $data;
    }
    $code_data = ["uniacid" => $uniacid, "data" => json_encode($data["data"], true)];
    $wechat_code_model = new app\Common\model\LongbingCardWechatCode();
    $code = longbingGetWxCode($code_id, $uniacid);
    if(empty($code)) {
        $code_data["id"] = $code_id;
        $result = $wechat_code_model->createCode($code_data);
    } else {
        $result = $wechat_code_model->updateCode(["id" => $code_id], $code_data);
    }
    longbingGetWxCode($code_id, $uniacid, true);
    if(empty($result)) {
        return false;
    }
    $path = NULL;
    $with = 430;
    $auto_color = true;
    $line_color = "{\"r\":0,\"g\":0,\"b\":0}";
    $is_hyaline = false;
    if(isset($data["path"])) {
        $path = $data["path"];
    }
    if(isset($data["with"])) {
        $with = $data["with"];
    }
    if(isset($data["auto_color"])) {
        $auto_color = $data["auto_color"];
    }
    if(isset($data["line_color"])) {
        $line_color = $data["line_color"];
    }
    if(isset($data["is_hyaline"])) {
        $is_hyaline = $data["is_hyaline"];
    }
    $wechat_code_model = new app\Common\WeChatCode($uniacid);
    switch ($type) {
        case 1:
            $result = $wechat_code_model->getQRCode($path, $width = 430);
            break;
        case 2:
            $result = $wechat_code_model->getWxCode($path, $width = 430, $auto_color = true, $line_color = "{\"r\":0,\"g\":0,\"b\":0}", $is_hyaline = false);
            break;
        default:
            $result = $wechat_code_model->getUnlimitedCode($code_id, $page, $width = 430, $auto_color = false, $line_color = "{\"r\":0,\"g\":0,\"b\":0}", $is_hyaline = true);
    }
    $data = json_decode($result, true);
    if(isset($data["errcode"]) || isset($data["errmsg"])) {
        return false;
    }
    $path = "image/" . $uniacid . "/" . "wxcode";
    $file_name = $code_id . ".jpeg";
    $path = $path . "/" . $file_name;
    if(longbinghaslocalfile($path)) {
        unlink(FILE_UPLOAD_PATH . $path);
    }
    $data = file_put_contents(FILE_UPLOAD_PATH . $path, $result);
    $data = ["qr_path" => $path, "path" => $path];
    if($type == 3) {
        $qr = transImagesOne($data, ["qr_path"], $uniacid);
        return $qr;
    }
    return $data;
}
function longbingGetWxCode($code_id, $uniacid, $is_update = false)
{
    $key = "longbing_wechat_code_" . $code_id;
    $data = NULL;
    $wechat_code_model = new app\Common\model\LongbingCardWechatCode();
    $data = $wechat_code_model->getCode(["id" => $code_id, "uniacid" => $uniacid]);
    if(!empty($data) && isset($data["data"])) {
        $data["data"] = json_decode($data["data"], true);
    }
    return $data;
}
function curlDownFile($file_url, $save_path = "", $file_name = "")
{
    if(trim($file_url) == "" || file_exists($save_path . $file_name)) {
        return false;
    }
    if(trim($save_path) == "") {
        $save_path = "./";
    }
    if(!file_exists($save_path) && !mkdir($save_path, 511, true)) {
        return false;
    }
    if(trim($file_name) == "") {
        $file_ext = strrchr($file_url, ".");
        $file_exts = [".gif", ".jpg", ".png", "mp3"];
        if(!in_array($file_ext, $file_exts)) {
            return false;
        }
        $file_name = time() . $file_ext;
    }
    $ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_URL, $file_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
    $file = curl_exec($ch);
    curl_close($ch);
    file_put_contents($save_path . $file_name, $file);
    unset($file);
    return true;
}

?>